package org.codehaus.activemq.store.jdbc.adapter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.codehaus.activemq.store.jdbc.StatementProvider;

public class StreamJDBCAdapter extends DefaultJDBCAdapter {
	public StreamJDBCAdapter() {
	}

	public StreamJDBCAdapter(StatementProvider provider) {
		super(provider);
	}

	protected byte[] getBinaryData(ResultSet rs, int index) throws SQLException {
		try {
			InputStream is = rs.getBinaryStream(index);
			ByteArrayOutputStream os = new ByteArrayOutputStream(4096);
			int ch;
			while ((ch = is.read()) >= 0) {
				os.write(ch);
			}
			is.close();
			os.close();

			return os.toByteArray();
		} catch (IOException e) {
			
			throw ((SQLException) new SQLException("Error reading binary parameter: " + index).initCause(e));
		}
	}

	protected void setBinaryData(PreparedStatement s, int index, byte[] data) throws SQLException {
		s.setBinaryStream(index, new ByteArrayInputStream(data), data.length);
	}
}